<template>
    
    <el-container>
        <el-header style="background: #fff; padding: 0; ">
            <div class="nav-api-header">
                <div style="padding-top: 10px; margin-left: 10px">
                    <el-dialog
                        title="选择项目"
                        :visible.sync="dialogVisible2"
                        width="30%"
                        align="center"
                        :close-on-click-modal="false"	
                        :show-close="false"
                    >
                        <el-select v-model="projectid" filterable  placeholder="请选择项目">
                            <el-option
                            v-for="item in ProjectList"
                            :key="item.name"
                            :label="item.name"
                            :value="item.id">
                            </el-option>
                        </el-select>
                        <p style="font-size:20px;color:red" v-show="tips">请选择项目</p>
                        <span slot="footer" class="dialog-footer">
                        <!-- <el-button size="small" @click="dialogVisible2 = false">取 消</el-button> -->
                        <el-button size="small" type="primary" @click="initdata">确 定</el-button>
                      </span>
                     </el-dialog>
                    <el-button
                        :disabled="addAPIFlag"
                        type="primary"
                        size="small"
                        icon="el-icon-circle-plus"
                        @click="dialogVisible = true"
                    >
                        新建分组
                    </el-button>

                    <el-dialog
                        title="新建分组"
                        :visible.sync="dialogVisible"
                        width="30%"
                        align="center"
                    >
                        <el-form
                            :model="nodeForm"
                            :rules="rules"
                            ref="nodeForm"
                            label-width="100px"
                            class="project">
                            <el-form-item label="节点名称" prop="name">
                                <el-input v-model="nodeForm.name"></el-input>
                            </el-form-item>
                        </el-form>

                        <el-radio-group v-model="radio" size="small">
                            <el-radio-button label="根节点"></el-radio-button>
                            <el-radio-button label="子节点"></el-radio-button>
                        </el-radio-group>

                        <span slot="footer" class="dialog-footer">
                        <el-button size="small" @click="dialogVisible = false">取 消</el-button>
                        <el-button size="small" type="primary" @click="handleConfirm('nodeForm')">确 定</el-button>
                      </span>
                    </el-dialog>
                    <el-button
                        :disabled="currentNode === '' || addAPIFlag "
                        type="danger"
                        size="small"
                        icon="el-icon-delete"
                        @click="deleteNode"
                    >删除分组
                    </el-button>


                    <el-button
                        :disabled="currentNode === '' || addAPIFlag "
                        type="info"
                        size="small"
                        icon="el-icon-refresh-right"
                        @click="renameNode"
                        style="margin-left: 0px"
                    >重命名
                    </el-button>


                    <el-button
                        type="primary"
                        size="small"
                        icon="el-icon-circle-plus"
                        @click="run = !run"
                        title="批量添加API"
                    >批量保存</el-button>

                    <el-button
                        v-if="!addAPIFlag"
                        type="danger"
                        icon="el-icon-delete"
                        circle
                        size="mini"
                        @click="del = !del"
                        title="批量删除"
                    ></el-button>
                   

                    <el-button
                        type="text"
                        style="position: absolute; right: 30px;"
                        @click="backapilistpage"
                    >返回项目接口列表</el-button>
                </div>
            </div>
        </el-header>

        <el-container>
            <el-aside style="margin-top: 10px;" v-show="!addAPIFlag">
                <div class="nav-api-side">
                    <div class="api-tree">
                        <el-input
                            placeholder="输入关键字进行过滤"
                            v-model="filterText"
                            v-if="dataTree.length!==0"
                            size="medium"
                            clearable
                            prefix-icon="el-icon-search"
                        >
                        </el-input>
                        <el-tree
                            @node-click="handleNodeClick"
                            :data="dataTree"
                            node-key="id"
                            :default-expand-all="false"
                            :expand-on-click-node="false"
                            draggable
                            highlight-current
                            :filter-node-method="filterNode"
                            ref="tree2"
                            @node-drag-end="handleDragEnd"
                        >
                            <span class="custom-tree-node"
                                  slot-scope="{ node, data }"
                            >
                                <span><i class="iconfont" v-html="expand"></i>&nbsp;&nbsp;{{ node.label }}</span>
                            </span>
                        </el-tree>
                    </div>

                </div>

            </el-aside>

            <el-main style="padding: 0;">
                <ChromeApiList
                    v-show="!addAPIFlag"
                    v-on:api="handleAPI"
                    :node="currentNode !== '' ? currentNode.id : '' "
                    :project="projectid"
                    :del="del"
                    :back="back"
                    :run="run"
                >
                </ChromeApiList>

            </el-main>
        </el-container>
    </el-container>

</template>
<script>
    import ChromeApiList from './components/ChromeApiList'

    export default {
        watch: {
            filterText(val) {
                this.$refs.tree2.filter(val);
            }
        },
        components: {
            ChromeApiList
        },

        data() {
            return {
                tips:false,
                projectid:"",
                ProjectList:[],
                back: false,
                del: false,
                run: false,
                nodeForm: {
                    name: '',
                },
                rules: {
                    name: [
                        {required: true, message: '请输入节点名称', trigger: 'blur'},
                        {min: 1, max: 50, message: '最多不超过50个字符', trigger: 'blur'}
                    ]
                },
                radio: '根节点',
                addAPIFlag: false,
                treeId: '',
                maxId: '',
                dialogVisible: false,
                dialogVisible2: false,
                currentNode: '',
                data: '',
                filterText: '',
                expand: '&#xe65f;',
                dataTree: [],
                apiData: {
                    count: 0,
                    results: []
                },
                dataKey:"",
            }
        },
        methods: {
            handleDragEnd() {
                this.updateTree(false);
            },
            handleAddSuccess() {
                this.back = !this.back;
                this.addAPIFlag = false;
            },

            handleAPI(response) {
                this.addAPIFlag = true;
                this.response = response;
            },
            initdata(){
                if(this.projectid==""){
                    this.tips=true
                    return
                }
                this.getTree();
                this.dialogVisible2=false
             
            },
            getProjectList() {
                this.$api.getProjectList().then(resp => {
                    this.ProjectList = resp.data.results
                    console.log("ProjectList",this.ProjectList)

                })
            },
  
           getAPIList() {
               this.$api.getApiList(this.dataKey).then(res=>{
                    this.apiData = res;
                })
                this.loading = false;
            
            },
            getTree() {
                // console.log(this.projectid)
                this.$api.getTree(this.projectid, {params: {type: 1}}).then(resp => {
                    this.dataTree = resp['tree'];
                    this.treeId = resp['id'];
                    this.maxId = resp['max'];
                })
            },

            updateTree(mode) {
                this.$api.updateTree(this.treeId, {
                    body: this.dataTree,
                    node: this.currentNode.id,
                    mode: mode,
                    type: 1
                }).then(resp => {
                    if (resp['success']) {
                        this.dataTree = resp['tree'];
                        this.maxId = resp['max'];
                        this.$notify.success('更新成功')
                    } else {
                        this.$message.error(resp['msg']);
                    }
                })
            },

            deleteNode() {
                this.$confirm('此操作将永久删除该节点下所有接口, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    if (this.currentNode === '') {
                        this.$notify.info('请选择一个节点');
                    } else {
                        if (this.currentNode.children.length !== 0) {
                            this.$notify.error('此节点有子节点，不可删除！');
                        } else {
                            this.remove(this.currentNode, this.data);
                            this.updateTree(true);
                        }
                    }
                })
            },

            renameNode() {
                this.$prompt('请输入节点名', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    inputPattern: /\S/,
                    inputErrorMessage: '节点名称不能为空'
                }).then(({value}) => {
                    const parent = this.data.parent;
                    const children = parent.data.children || parent.data;
                    const index = children.findIndex(d => d.id === this.currentNode.id);
                    children[index]["label"] = value
                    this.updateTree(false);
                });
            },

            handleConfirm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.append(this.currentNode);
                        this.updateTree(false);
                        this.dialogVisible = false;
                    }
                });
            },

            handleNodeClick(node, data) {
                this.addAPIFlag = false;
                this.currentNode = node;
                // this.data = data;
            },

            filterNode(value, data) {
                if (!value) return true;
                return data.label.indexOf(value) !== -1;
            },

            remove(data, node) {
                const parent = node.parent;
                const children = parent.data.children || parent.data;
                const index = children.findIndex(d => d.id === data.id);
                children.splice(index, 1);
            },

            append(data) {
                const newChild = {id: ++this.maxId, label: this.nodeForm.name, children: []};
                if (data === '' || this.dataTree.length === 0 || this.radio === '根节点') {
                    this.dataTree.push(newChild);
                    return
                }
                if (!data.children) {
                    this.$set(data, 'children', []);
                }
                data.children.push(newChild);
            },
            backapilistpage(){
                this.$router.push({ path:'/fastrunner/api_record/'+this.projectid})
            },
            pageInitCheck(){
                //获取url参数判断是文件导入页面进来还是谷歌插件录制，如果导入页面进来，不弹项目选择直接获取项目的tree
                let query=this.$route.query;
                this.dataKey=query.datakey;
                
                if (!query.hasOwnProperty("projectid")){
                    this.getProjectList()
                    this.dialogVisible2=true
                }
                else{
                    this.projectid=query.projectid
                    this.getTree();

                }

                this.getAPIList()
                console.log("url参数", this.$route.query)
                },
        },
        name: "RecordChromeApi",
        mounted() {
           this.pageInitCheck()
        }
    }
</script>

<style scoped>


</style>
